import { forwardRef, useImperativeHandle, useState,useRef, useEffect } from "react";
import "./index.scss"
import { createPortal } from 'react-dom';

export type ModalInstanceType = {
  openModal: (message:string) => void,
  closeModal: () => void,
}
const Modal = forwardRef<ModalInstanceType>((props, ref) => {
  const [showModal, setShowModal] = useState(false)
  const [message, setMessage] = useState('')
  const divRef = useRef<HTMLDivElement>(document.createElement('div'))
  const divElement = divRef.current;
  useImperativeHandle(ref, () => ({
    openModal: (message) => {
      setShowModal(true)
      if(message) setMessage(message)
      setTimeout(() => setShowModal(false), 2000)
    },
    closeModal: () => setShowModal(false)
  }))

  useEffect(() => {
    if(showModal){
      document.body.appendChild(divElement);
    }else{
      divElement.parentNode && document.body.removeChild(divElement);
    }
    return () => {
      divElement.parentNode && document.body.removeChild(divElement);
    }
  }, [showModal])
  
  return showModal ? createPortal(<div className="modal">
    <div className="modal-text">{message}</div>
  </div>,divElement):null;
})


export default Modal;